<script setup lang="ts">

defineOptions({name: 'RoleMenuAllocation'})
import {getIsMobile, makeTree, arrayGroupBy, delObjEmptyVal} from "@/utils/helper"
import {useI18n} from "vue-i18n"
import {getMenuList} from '@/api/menu'
import {getRoleMenuList, settingRoleMenu} from '@/api/role-menu'

const dataId = ref<number | string>(0);
const formRef = ref()
const visible = ref<boolean>(false)
const disabledSubmit = ref<boolean>(false)
const isMobile = getIsMobile()
const {t} = useI18n()
const treeData = ref<any>([])
const treeRef = ref()
const treeCheckedKeys = ref<any>([])
const formData = ref<any>({})
const formItems = ref<any>([{label: '', key: 'tree', type: 'tree', span: 24}])

const handleReset = () => {
	if (!treeRef.value) return false
	treeRef.value.setCheckedKeys(treeCheckedKeys.value)
}

const handleSubmit = async () => {
	if (!treeRef.value) return false
	if (disabledSubmit.value) return false
	disabledSubmit.value = true
	const checkedKeys = treeRef.value.getCheckedKeys(false)
	const halfCheckedKeys = treeRef.value.getHalfCheckedKeys()
	const menuIds = [...checkedKeys, ...halfCheckedKeys]
	const sendData: any = {
		roleId: dataId.value,
		menuIds: Array.from(new Set(menuIds))
	}
	delObjEmptyVal(sendData)
	try {
		await settingRoleMenu(sendData)
		setTimeout(() => {
			close()
		}, 600)
	} catch (error) {
		console.error('[RoleMenuAllocation] Unexpected error:', error)
	} finally {
		setTimeout(() => {
			disabledSubmit.value = false
		}, 800);
	}
}

const getData = async () => {
	const getMenuRes: any = await getMenuList({page: 1, limit: 1000})
	const temp: any = []
	getMenuRes.list.forEach((item: any) => {
		temp.push({
			label: t(item.title),
			value: item.menuId,
			pid: item.pid
		})
	})
	treeData.value = makeTree(temp, 'value', 'pid', 0)
	const getRoleMenuRes: any = await getRoleMenuList({page: 1, limit: 1000, roleId: dataId.value})
	const menuGroup: any = arrayGroupBy(getMenuRes.list, ['pid'])
	const checkedKeys: any = []
	getRoleMenuRes.list.forEach((item: any) => {
		if (!menuGroup[item.menuId]) {
			checkedKeys.push(item.menuId);
		}
	});
	treeRef.value.setCheckedKeys(checkedKeys)
	treeCheckedKeys.value = checkedKeys
}

const open = (id: any): void => {
	visible.value = true
	dataId.value = id
	getData()
}

const close = () => visible.value = false

defineExpose({open, close})
</script>

<template>
	<div class="form-operate-box">
		<ElDialog
			v-model="visible" :title="t('module.role.operate.menuAllocation')"
			:width="isMobile ? '100%' : '500px'"
			:close-on-click-modal="false" :align-center="true" :draggable="true" :destroy-on-close="true"
		>
			<ArtForm
				ref="formRef"
				labelPosition="top"
				v-model="formData"
				:items="formItems"
				:disabledSubmit="disabledSubmit"
				:showReset="false"
				@close="close"
				@reset="handleReset"
				@submit="handleSubmit"
			>
				<template #tree>
					<ElTree
						ref="treeRef"
						:data="treeData"
						:show-checkbox="true"
						:default-expand-all="true"
						:highlight-current="true"
						node-key="value"
						style="width: 100%;"
					/>
				</template>
			</ArtForm>
		</ElDialog>
	</div>
</template>

<style scoped lang="scss">
.form-operate-box {
	:deep(.el-form-item--label-top .el-form-item__label) {
		margin-left: 3px !important;
		margin-bottom: 2px !important;
	}

	:deep(.el-dialog__body) {
		padding: 0 !important;
	}

	:deep(.action-buttons-wrapper) {
		margin-top: 8px !important;
		justify-content: flex-end !important;
	}
}
</style>